package com.xiaoc.bulldozer.facade.impl;

import com.xc.framework.common.oss.AliOSS;
import com.xiaoc.bulldozer.common.ImageConstant;
import com.xiaoc.bulldozer.common.dto.WxCodeConfig;
import com.xiaoc.bulldozer.facade.PosterFacade;
import com.xiaoc.bulldozer.service.WxService;
import com.xiaoc.bulldozer.springboot.config.common.ConstantConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Service("posterFacade")
public class PosterFacadeImpl implements PosterFacade {

    private static final Logger logger = LoggerFactory.getLogger(PosterFacadeImpl.class);

    @Resource(name = "wxService")
    private WxService wxService;

    @Resource
    private AliOSS aliOss;

    @Override
    public File generateWxCodeFile(boolean isChange, String secene, String folder, String imageName, String pagePath, int size, Integer r, Integer g, Integer b, boolean isHyaline) {

        if (!StringUtils.endsWith(imageName, ImageConstant.IMAGE_SUFFIX)) {
            imageName = imageName + ImageConstant.IMAGE_SUFFIX;
        }

        File wxCodeDir = new File(ConstantConfig.TEMP_DIR + "/" + folder);

        if (!wxCodeDir.exists()) {
            wxCodeDir.mkdirs();
        }

        String wxCodeName = folder + "/" + imageName;

        File wxCodeFile = new File(wxCodeDir + "/" + imageName);

        return this.getAndUploadCodeImage(isChange, secene, wxCodeName, wxCodeFile, pagePath, size, r, g, b, isHyaline);
    }

    @Override
    public File getAndUploadCodeImage(boolean isChange, String secene, String wxCodeName, File wxCodeFile, String pagePath, int size, Integer r, Integer g, Integer b, boolean isHyaline) {

        if (isChange || !aliOss.doesFileExist(wxCodeName)) {
            String accessToken = wxService.getAccessToken();

            if (StringUtils.isEmpty(accessToken)) {
                logger.error("accessToken is null");
            }

            WxCodeConfig wxCodeConfig = new WxCodeConfig(secene, pagePath, size, false, isHyaline);
            Map<String, Integer> lineColorMap = wxCodeConfig.getLineColor();
            if (lineColorMap == null) {
                lineColorMap = new HashMap<String, Integer>();
                wxCodeConfig.setLineColor(lineColorMap);
            }
            lineColorMap.put("r", r);
            lineColorMap.put("g", g);
            lineColorMap.put("b", b);

            wxCodeFile = wxService.generateWxCode(accessToken, wxCodeConfig, wxCodeFile);
            aliOss.uploadFile(wxCodeName, wxCodeFile);
        }

        wxCodeFile = aliOss.getFile(wxCodeName, wxCodeFile);
        return wxCodeFile;
    }
}
